<template>
  <div class="document-detail-container">
    <div class="document-detail-content">
      <!-- 文档头部 -->
      <div class="document-header">
        <div class="header-left">
          <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
          <div class="document-info">
            <h1 class="document-title">{{ document.title }}</h1>
            <div class="document-meta">
              <span class="author">
                <el-icon><User /></el-icon>
                {{ document.authorName }}
              </span>
              <span class="category" v-if="document.categoryName">
                <el-icon><Folder /></el-icon>
                {{ document.categoryName }}
              </span>
              <span class="update-time">
                <el-icon><Clock /></el-icon>
                {{ formatTime(document.updateTime) }}
              </span>
              <span class="view-count">
                <el-icon><View /></el-icon>
                {{ document.viewCount || 0 }} 次查看
              </span>
            </div>
          </div>
        </div>
        
        <div class="header-actions">
          <el-button-group>
            <el-button icon="Star" :type="document.isFavorite ? 'primary' : 'default'" @click="toggleFavorite">
              {{ document.isFavorite ? '已收藏' : '收藏' }}
            </el-button>
            <el-button icon="Share" @click="shareDocument">分享</el-button>
            <el-button icon="Download" @click="exportDocument">导出</el-button>
          </el-button-group>
          <el-button 
            v-if="canEdit" 
            type="primary" 
            icon="Edit" 
            @click="editDocument"
          >
            编辑
          </el-button>
        </div>
      </div>

      <!-- 文档内容 -->
      <div class="document-body">
        <div class="document-content">
          <el-card>
            <div class="markdown-content" v-html="renderedContent"></div>
          </el-card>
        </div>

        <!-- 侧边栏 -->
        <div class="document-sidebar">
          <!-- 目录 -->
          <el-card class="toc-card">
            <template #header>
              <span>目录</span>
            </template>
            <div class="table-of-contents">
              <div 
                v-for="heading in tableOfContents"
                :key="heading.id"
                :class="['toc-item', `level-${heading.level}`]"
                @click="scrollToHeading(heading.id)"
              >
                {{ heading.text }}
              </div>
            </div>
          </el-card>

          <!-- 文档信息 -->
          <el-card class="info-card">
            <template #header>
              <span>文档信息</span>
            </template>
            <div class="document-stats">
              <div class="stat-item">
                <span class="label">字数：</span>
                <span class="value">{{ wordCount }}</span>
              </div>
              <div class="stat-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(document.createTime) }}</span>
              </div>
              <div class="stat-item">
                <span class="label">最后修改：</span>
                <span class="value">{{ formatDate(document.updateTime) }}</span>
              </div>
              <div class="stat-item" v-if="document.tags && document.tags.length">
                <span class="label">标签：</span>
                <div class="tags">
                  <el-tag 
                    v-for="tag in document.tags"
                    :key="tag"
                    size="small"
                    type="info"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 版本历史 -->
          <el-card class="versions-card">
            <template #header>
              <div class="versions-header">
                <span>版本历史</span>
                <el-button type="text" size="small" @click="viewAllVersions">查看全部</el-button>
              </div>
            </template>
            <div class="versions-list">
              <div 
                v-for="version in recentVersions"
                :key="version.id"
                class="version-item"
                @click="viewVersion(version)"
              >
                <div class="version-info">
                  <div class="version-title">{{ version.title || '版本更新' }}</div>
                  <div class="version-time">{{ formatTime(version.createTime) }}</div>
                </div>
                <div class="version-author">{{ version.authorName }}</div>
              </div>
            </div>
          </el-card>

          <!-- 相关文档 -->
          <el-card class="related-card" v-if="relatedDocuments.length">
            <template #header>
              <span>相关文档</span>
            </template>
            <div class="related-list">
              <div 
                v-for="doc in relatedDocuments"
                :key="doc.id"
                class="related-item"
                @click="goToDocument(doc.id)"
              >
                <div class="related-title">{{ doc.title }}</div>
                <div class="related-meta">
                  <span>{{ doc.authorName }}</span>
                  <span>{{ formatTime(doc.updateTime) }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 评论区 -->
      <div class="document-comments">
        <el-card>
          <template #header>
            <div class="comments-header">
              <span>评论 ({{ comments.length }})</span>
              <el-button type="primary" @click="showCommentDialog = true">写评论</el-button>
            </div>
          </template>
          <div class="comments-list">
            <div 
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-user">
                <el-avatar :src="comment.userAvatar" :size="40" />
                <div class="user-info">
                  <div class="username">{{ comment.username }}</div>
                  <div class="comment-time">{{ formatTime(comment.createTime) }}</div>
                </div>
              </div>
              <div class="comment-content">
                {{ comment.content }}
              </div>
              <div class="comment-actions">
                <el-button type="text" size="small" @click="replyComment(comment)">回复</el-button>
                <el-button type="text" size="small" @click="likeComment(comment)">
                  <el-icon><Like /></el-icon>
                  {{ comment.likeCount || 0 }}
                </el-button>
              </div>
            </div>
          </div>
          <div v-if="comments.length === 0" class="no-comments">
            暂无评论，快来写下第一个评论吧！
          </div>
        </el-card>
      </div>
    </div>

    <!-- 评论对话框 -->
    <el-dialog
      v-model="showCommentDialog"
      title="写评论"
      width="500px"
    >
      <el-input
        v-model="commentContent"
        type="textarea"
        :rows="4"
        placeholder="请输入您的评论..."
      />
      <template #footer>
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment" :loading="submitting">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getDocumentDetail,
  getDocumentVersions,
  getRelatedDocuments,
  getDocumentComments,
  addDocumentComment,
  favoriteDocument,
  unfavoriteDocument
} from '@/api/document'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const document = ref({})
const recentVersions = ref([])
const relatedDocuments = ref([])
const comments = ref([])
const tableOfContents = ref([])
const showCommentDialog = ref(false)
const commentContent = ref('')
const submitting = ref(false)

// 计算属性
const renderedContent = computed(() => {
  // 这里应该使用 markdown 解析器，简化处理
  if (!document.value.content) return ''
  return document.value.content.replace(/\n/g, '<br>')
})

const wordCount = computed(() => {
  if (!document.value.content) return 0
  return document.value.content.length
})

const canEdit = computed(() => {
  // 检查是否有编辑权限
  return document.value.canEdit || false
})

// 页面加载
onMounted(async () => {
  await loadDocument()
  await loadVersions()
  await loadRelatedDocuments()
  await loadComments()
})

// 加载文档详情
const loadDocument = async () => {
  try {
    const response = await getDocumentDetail(route.params.id)
    if (response.code === 200) {
      document.value = response.data
      generateTableOfContents()
    } else {
      ElMessage.error('获取文档详情失败')
    }
  } catch (error) {
    console.error('获取文档详情失败:', error)
    ElMessage.error('获取文档详情失败')
  }
}

// 加载版本历史
const loadVersions = async () => {
  try {
    const response = await getDocumentVersions(route.params.id)
    if (response.code === 200) {
      recentVersions.value = (response.data || []).slice(0, 5)
    }
  } catch (error) {
    console.error('获取版本历史失败:', error)
  }
}

// 加载相关文档
const loadRelatedDocuments = async () => {
  try {
    const response = await getRelatedDocuments(route.params.id)
    if (response.code === 200) {
      relatedDocuments.value = response.data || []
    }
  } catch (error) {
    console.error('获取相关文档失败:', error)
  }
}

// 加载评论
const loadComments = async () => {
  try {
    const response = await getDocumentComments(route.params.id)
    if (response.code === 200) {
      comments.value = response.data || []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 生成目录
const generateTableOfContents = () => {
  if (!document.value.content) return
  
  const headings = []
  const lines = document.value.content.split('\n')
  
  lines.forEach((line, index) => {
    const match = line.match(/^(#{1,6})\s+(.+)/)
    if (match) {
      headings.push({
        id: `heading-${index}`,
        level: match[1].length,
        text: match[2],
        line: index
      })
    }
  })
  
  tableOfContents.value = headings
}

// 滚动到标题
const scrollToHeading = (headingId) => {
  const element = document.getElementById(headingId)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

// 切换收藏
const toggleFavorite = async () => {
  try {
    if (document.value.isFavorite) {
      await unfavoriteDocument(document.value.id)
      document.value.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      await favoriteDocument(document.value.id)
      document.value.isFavorite = true
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分享文档
const shareDocument = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 导出文档
const exportDocument = () => {
  const blob = new Blob([document.value.content || ''], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${document.value.title || '文档'}.md`
  a.click()
  URL.revokeObjectURL(url)
}

// 编辑文档
const editDocument = () => {
  router.push(`/document/${document.value.id}/edit`)
}

// 查看版本
const viewVersion = (version) => {
  router.push(`/document/${document.value.id}/version/${version.id}`)
}

// 查看所有版本
const viewAllVersions = () => {
  router.push(`/document/${document.value.id}/versions`)
}

// 跳转到文档
const goToDocument = (docId) => {
  router.push(`/document/${docId}`)
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  try {
    submitting.value = true
    await addDocumentComment({
      documentId: document.value.id,
      content: commentContent.value
    })
    ElMessage.success('评论提交成功')
    showCommentDialog.value = false
    commentContent.value = ''
    loadComments()
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('提交评论失败')
  } finally {
    submitting.value = false
  }
}

// 回复评论
const replyComment = (comment) => {
  commentContent.value = `@${comment.username} `
  showCommentDialog.value = true
}

// 点赞评论
const likeComment = async (comment) => {
  try {
    // 这里应该调用点赞API
    comment.likeCount = (comment.likeCount || 0) + 1
    ElMessage.success('点赞成功')
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败')
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}
</script>

<style lang="scss" scoped>
.document-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.document-detail-content {
  max-width: 1400px;
  margin: 0 auto;
}

.document-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .header-left {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    flex: 1;
    
    .document-info {
      .document-title {
        font-size: 28px;
        font-weight: 600;
        margin: 0 0 16px 0;
        color: #303133;
      }
      
      .document-meta {
        display: flex;
        align-items: center;
        gap: 20px;
        flex-wrap: wrap;
        
        span {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.document-body {
  display: flex;
  gap: 20px;
  
  .document-content {
    flex: 1;
    
    .markdown-content {
      min-height: 400px;
      line-height: 1.8;
      font-size: 16px;
      color: #303133;
      
      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin: 20px 0 10px 0;
        color: #303133;
      }
      
      :deep(p) {
        margin: 12px 0;
      }
      
      :deep(img) {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
      }
      
      :deep(code) {
        background-color: #f5f5f5;
        padding: 2px 4px;
        border-radius: 3px;
        font-family: 'Monaco', 'Consolas', monospace;
      }
      
      :deep(pre) {
        background-color: #f5f5f5;
        padding: 16px;
        border-radius: 4px;
        overflow-x: auto;
      }
    }
  }
  
  .document-sidebar {
    width: 300px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .toc-card,
    .info-card,
    .versions-card,
    .related-card {
      .table-of-contents {
        .toc-item {
          padding: 4px 0;
          cursor: pointer;
          color: #606266;
          
          &:hover {
            color: #409eff;
          }
          
          &.level-1 { padding-left: 0; font-weight: 600; }
          &.level-2 { padding-left: 16px; }
          &.level-3 { padding-left: 32px; }
          &.level-4 { padding-left: 48px; }
          &.level-5 { padding-left: 64px; }
          &.level-6 { padding-left: 80px; }
        }
      }
      
      .document-stats {
        .stat-item {
          display: flex;
          justify-content: space-between;
          margin: 12px 0;
          
          .label {
            color: #909399;
          }
          
          .value {
            color: #303133;
          }
          
          .tags {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
          }
        }
      }
      
      .versions-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .versions-list,
      .related-list {
        .version-item,
        .related-item {
          padding: 12px 0;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
          
          &:last-child {
            border-bottom: none;
          }
          
          &:hover {
            background-color: #f8f9fa;
          }
          
          .version-info,
          .related-title {
            .version-title,
            .related-title {
              font-weight: 500;
              color: #303133;
              margin-bottom: 4px;
            }
            
            .version-time {
              font-size: 12px;
              color: #909399;
            }
          }
          
          .version-author {
            font-size: 12px;
            color: #606266;
          }
          
          .related-meta {
            display: flex;
            gap: 8px;
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
}

.document-comments {
  margin-top: 40px;
  
  .comments-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .comments-list {
    .comment-item {
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .comment-user {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;
        
        .user-info {
          .username {
            font-weight: 500;
            color: #303133;
          }
          
          .comment-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }
      
      .comment-content {
        color: #606266;
        line-height: 1.5;
        margin-bottom: 8px;
      }
      
      .comment-actions {
        display: flex;
        gap: 16px;
      }
    }
  }
  
  .no-comments {
    text-align: center;
    color: #909399;
    padding: 40px 0;
  }
}

@media (max-width: 768px) {
  .document-detail-container {
    padding: 10px;
  }
  
  .document-header {
    flex-direction: column;
    gap: 20px;
    padding: 20px;
    
    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .document-body {
    flex-direction: column;
    
    .document-sidebar {
      width: 100%;
    }
  }
  
  .document-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
